<script setup lang="ts">
// 引入用户小仓库
import useUserStore from '@/store/modules/user'
import { GET_CODEVERIFIER, GET_STATE, getQueryString, SET_CODEVERIFIER, SET_STATE } from '@/utils/globalUtils'
import { generateCodeChallenge, generateCodeVerifier } from '@/utils/pkce'
import { ElMessage } from 'element-plus'

// 使用用户小仓库
const userStore = useUserStore()

// 生成CodeVerifier
const codeVerifier: string = generateCodeVerifier()
// codeChallenge
const codeChallenge: string = generateCodeChallenge(codeVerifier)
// 生成state
const state: string = generateCodeVerifier()

// 获取地址栏授权码
const code = getQueryString('code')

if (code) {
  // 从缓存中获取 codeVerifier
  const state = GET_STATE()
  // 校验state，防止cors
  const urlState = getQueryString('state')
  if (urlState !== state) {
    ElMessage({
      message: 'state校验失败.',
      type: 'warning',
    })
  }
  else {
    // 从缓存中获取 codeVerifier
    const code_verifier = GET_CODEVERIFIER()
    // 调用用户小仓库的getToken方法
    userStore.getToken({
      grant_type: 'authorization_code',
      client_id: import.meta.env.VITE_PKCE_CLIENT_ID,
      redirect_uri: import.meta.env.VITE_PKCE_REDIRECT_URI,
      code,
      code_verifier,
      state,
    })
  }
}
else {
  // 缓存state
  SET_STATE(state)
  // 缓存codeVerifier
  SET_CODEVERIFIER(codeVerifier)
  window.location.href = `${
    import.meta.env.VITE_OAUTH_ISSUER
  }/oauth2/authorize?response_type=code&client_id=${
    import.meta.env.VITE_PKCE_CLIENT_ID
  }&redirect_uri=${encodeURIComponent(
    import.meta.env.VITE_PKCE_REDIRECT_URI,
  )}&scope=message.write%20message.read&code_challenge=${codeChallenge}&code_challenge_method=S256&state=${state}`
}
</script>

<template>
  加载中...
</template>
